<template>
  <div>
    <div v-show="false">
      <button @click="getToken">geyToken</button>
      <button @click="getWLLD">获取订单信息</button>
      <button @click="formatResData">格式化shujv</button>
      <button @click="verifyToken">verifyToken</button>
      <button @click="refreshToken">refreshToken</button>
      <div> 刷新时间：{{ lastrefreshtime }}</div>
    </div>
    <div v-show="errmsg" class="msgbox">
      <span>{{ errmsg }}</span>
    </div>
    <div v-show="!errmsg" class="listbox">
      <table>
        <tr>
          <th>单据编号</th>
          <th>供应商</th>
          <th>物料</th>
          <th>收货单位</th>
          <th>送货码</th>
          <th>车牌号</th>
        </tr>
        <tr v-for="(item, index) in ddlist" :key="index">
          <td>{{ item.billno }}</td>
          <td>{{ item.supplier_name }}</td>
          <td>{{ item.material_masterid_name }}</td>
          <td>{{ item.org_name }}</td>
          <td>{{ item.vc }}</td>
          <td>{{ item.plate }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      token: "",
      errmsg: "",
      ddlist: [],
      lastrefreshtime: "",
    };
  },
  methods: {
    // 格式化时间
    formatDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 获取token
    async getToken() {
      const reqdata = {
        client_id: "jlxmtest",
        client_secret: "jlxm.QDJL.20241230.01231425531",
        username: "郑圣龙",
        accountId: "",
        language: "zh_CN",
        nonce: Date.now().toString(),
        timestamp: this.formatDate(),
      };
      await this.$http
        .post("oauth2/getToken", reqdata)
        .then((res) => {
          console.log("res", res);
          this.token = res.data.data.access_token;
          localStorage.setItem("token", res.data.data.access_token);
          localStorage.setItem("refresh_token", res.data.data.refresh_token);
        })
        .catch((err) => {
          this.errmsg = "出现异常联系管理员检查：" + err.message;
        });
      console.log("getToken", this.token);
    },
    // 获取订单信息
    async getWLLD() {
      await this.verifyToken();
      const params = {
        page: 1,
        pageSize: 100,
      };
      await this.$http
        .get("v2/zn26/sd_wuliu/sd_wuliuorder/getwlddjl", {
          params,
          headers: {
            accesstoken: this.token,
          },
        })
        .then((res) => {
          this.formatResData(res.data.data.rows);
          this.errmsg = "";
          console.log(res.data);
        })
        .catch((err) => {
          console.log(err);
          this.errmsg = "出现异常联系管理员检查：" + err.message;
        });
      this.lastrefreshtime = this.formatDate();
    },
    // 格式化数据
    formatResData(list) {
      const newArr = [];
      // 遍历原数组
      list.forEach((item) => {
        // 获取物料明细和派车计划的长度
        const entryLength = item.entryentity.length;
        const planLenght = item.paicheplan.length;

        // 计算需要循环的次数
        const macCount = Math.max(entryLength, planLenght);

        // 循环生成新的数组
        for (let i = 0; i < macCount; i++) {
          // 创建新对象
          const ogj = {
            billno: i === 0 ? item.billno : "",
            supplier_name: item.entryentity[i]?.supplier_name || "",
            material_masterid_name:
              item.entryentity[i]?.material_masterid_name || "",
            plate: item.paicheplan[i]?.plate || "",
            vc: item.vc,
            org_name: item.org_name,
          };

          // 添加数组元素
          newArr.push(ogj);
        }
      });
      this.ddlist = newArr;
    },
    // 检查token有效性
    async verifyToken() {
      const body = {
        client_id: "jlxmtest",
        token_type_hint: "access_token",
        // token: this.token,
        token: localStorage.getItem("token"),
        nonce: Date.now().toString(),
        timestamp: this.formatDate(),
        accountId: "",
      };
      await this.$http
        .post("oauth2/verifyToken", body)
        .then((res) => {
          console.log(res.data);
          if (res.data.errorCode === "0" && res.data.data.active === true) {
            console.log("token有效，继续===》");
          } else if (
            res.data.errorCode === "0" ||
            res.data.errorCode === "603" ||
            res.data.data.active === false
          ) {
            this.errmsg = "token无效, 正在重新获取";
            this.getToken();
          } else {
            this.errmsg = "出现异常联系管理员检查：" + res.data.message;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 刷新token市场
    async refreshToken() {
      const body = {
        client_id: "jlxmtest",
        grant_type: "refresh_token",
        refresh_token: localStorage.getItem("refresh_token"),
        accountId: "",
        nonce: Date.now().toString(),
        timestamp: this.formatDate(),
      };
      await this.$http
        .post("oauth2/refreshToken", body)
        .then((res) => {
          if (res.data.errorCode === "0") {
            localStorage.setItem("refresh_token", res.data.data.refresh_token);
            console.log("刷新token成功");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  created() {
    this.token = localStorage.getItem("token");
    this.getWLLD();
    // 定时器，每1分钟更新一次订单信息
    setInterval(() => {
      this.getWLLD();
    }, 1 * 60 * 1000);
    // 定时器，每10分钟刷新一次token
    setInterval(() => {
      this.refreshToken();
    }, 30 * 60 * 1000);
  },
};
</script>

<style>
body {
  background-color: #282b4d;
  color: #fff;
}

table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

th,
td {
  padding: 8px;
  border: 1px solid #fff;
}

th {
}

tr:nth-child(even) {
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50; /* #333 */
}
</style>
